import { login, getUserInfo, getUserDetailById } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    // 默认从本地读取 token
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 修改token
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    // 清除token
    REMOVE_TOKEN(state) {
      state.token = '' // 清除vuex里的token
      removeToken() // 清除cookie里的token
      // 重置路由
      resetRouter()
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async fetchLogin(store, loginForm) {
      const { data } = await login(loginForm)
      store.commit('SET_TOKEN', data)
      return data
    },
    async fetchUserInfo(store) {
      const res = await getUserInfo()
      const res2 = await getUserDetailById(res.data.userId)
      store.commit('SET_USERINFO', { ...res.data, ...res2.data })
      // console.log(res)
    }
  }
}
